//
//  M4LoanResultViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/20.
//

import UIKit
import KakaJSON

class M4LoanResultViewController: M4BaseViewController {

    private var recommendPros: [M4RecommendProsModel] = []
    
    private var M4ResultModel: M4LoanResultModel?
    
    var M4LoanId: Int = 0
    
    var M4PageFromLoan: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()

        M4NavTitle(M4Title: "Detalles del producto", M4NavTitleColor: .white)
        showSuggentionViewButton = true
        M4NavRightItem()
        let bgview = UIView()
        bgview.backgroundColor = COLOR_00479D
        self.view.addSubview(bgview)
        bgview.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(M4NavigationFullHeight()-0.5)
            make.height.equalTo(90)
        }
        self.view.addSubview(M4TableView)
        M4TableView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(M4NavigationFullHeight())
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-M4SafeDistanceBottom())
        }
        M4addRefreshToTaleView { [weak self] in
            self?.M4LoanResultNet()
        }
        
        M4LoanResultNet()
        var isSame: Bool = false
        let currentDate = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let currentYearMonthDay = dateFormatter.string(from: currentDate)
        let userDefaults = UserDefaults.standard
        if let savedDate = userDefaults.value(forKey: "M4SavedDate") as? String {
            if savedDate == currentYearMonthDay {
                isSame = true
            } else {
                isSame = false
            }
        } else {
            isSame = false
        }
//        let hours = (Int(Date().timeIntervalSince1970) - M4ConfigDataManager.m4ConfigShare.M4StarAlertTime) / 3600
        if M4UserDataManager.m4UserShare.M4AuditAccount != 1 && M4CreditStatusManager.m4CreditShare.m4isUserLimitRemark == 1 && !isSame {
//            M4ConfigDataManager.m4ConfigShare.M4StarAlertTime = Int(Date().timeIntervalSince1970)
            userDefaults.set(currentYearMonthDay, forKey: "M4SavedDate")
            userDefaults.synchronize()
            let alert = UINib(nibName: "M4PositiveReviewsAlertVIew", bundle: nil).instantiate(withOwner: self).last as? M4PositiveReviewsAlertVIew
            alert?.M4AlertViewShow()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        M4NavBarColor = COLOR_00479D
    }
    
    override func M4BackClick(sender: UIButton) {
        
       
        if M4PageFromLoan {
            let c = self.navigationController?.viewControllers.first
            let cName = String(describing: c)
            if let rootVC = UIApplication.shared.keyWindow?.rootViewController {
                let name = String(describing: rootVC)
                if name.contains("M4TabBarViewController") {
                    
                    self.navigationController?.popToRootViewController(animated: true)
                    
                }else{
                    AppDelegate.keyWindow()?.rootViewController = M4TabBarViewController()
                    
                }
                
            }
            
        }
        else {
            if let rootVC = UIApplication.shared.keyWindow?.rootViewController {
                let name = String(describing: rootVC)
                if name.contains("M4TabBarViewController") {
                    self.navigationController?.popViewController(animated: true)

                }else{
                    AppDelegate.keyWindow()?.rootViewController = M4TabBarViewController()

                }
                
            }
        }
    }
    
    override func M4CellAction(_ action: M4IDAction) {
        let yKhs = M4ResultModel?.QKDLhYTHobF?.first?.yKhs ?? 0
        let type = M4LoanResultAction(rawValue: action.M4ActionType)
        if type == .M4ResultPrivacyAction {
            let htmlVC = M4HtmlWebViewController()
            htmlVC.M4WebTitle = "Acuerdo de préstamo"
            htmlVC.M4WebUrl = M4NetworkAPI.m4htmlPath.rawValue + "/asdasd?vcxoPPo=\(M4UserDataManager.m4UserShare.M4Token)&sesaPPOs=\(yKhs)"
            self.navigationController?.pushViewController(htmlVC, animated: true)
        }
        else if type == .M4RecommendProAction {
            //点击产品跳转外部app
            let link = action.M4ActionData as? String
            guard let url = URL(string: link ?? ""),
                  UIApplication.shared.canOpenURL(url) else {
                self.view.makeToast("Tidak dapat menemukan tautan ini", position: .center)
                return
            }
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            } else {
                
            }
        }
        else if type == .M4ResultReturnHome {
            if self.navigationController?.viewControllers.first is M4FirstInfoViewController {
                AppDelegate.keyWindow()?.rootViewController = M4TabBarViewController()
            }
            else {
                self.navigationController?.popToRootViewController(animated: true)
            }
        }
    }
    
    override func M4DataRefresh() {
        M4LoanResultNet()
    }
    
}

extension M4LoanResultViewController {
    
    private func M4LoanResultDataSource() {
        M4TableSources.removeAll()
        M4TableSources.append(M4TableViewCellData("M4LoanResultCell", XIB: true, M4ResultModel ?? M4LoanResultModel(), recommendPros.count))
        recommendPros.forEach { pro in
            M4TableSources.append(M4TableViewCellData("M4HomeSecondCell", XIB: true, pro))
        }
        
        M4TableView.reloadData()
    }
    
    private func M4LoanResultNet() {
        let loading = M4LoadingAlertView()
        loading.M4LoadingAlertShow()
        let para: [String : Any] = ["YjWGJmF": "ESP", "DnVc": M4UserDataManager.m4UserShare.M4Itemcode, "ICfy": M4UserDataManager.m4UserShare.M4ProductCode, "IxENPg": M4UserDataManager.m4UserShare.M4Token, "IQAfZSgHc": M4LoanId]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4OrderDetail, .post, params: para), false) { model in
            if model.code == 1 {
                let data = model.data as? [String : Any]
                self.M4ResultModel = data?.kj.model(M4LoanResultModel.self)
                if self.M4ResultModel?.QKDLhYTHobF?.first?.VRFYc == 6 {//审核未通过
                    self.M4endRefresh()
                    loading.M4AlertViewHidden()
                    self.recommendPros = []
                    
                    self.M4LoanResultDataSource()
                } else {
                    self.M4RecommecdProsNet(loading: loading)
                }
            }
            else {
                loading.M4AlertViewHidden()
                self.M4endRefresh()
                self.view.makeToast(model.message, position: .center)
            }
        }
    }
    
    private func M4RecommecdProsNet(loading: M4LoadingAlertView) {
        let para: [String : Any] = ["UJLMh": "ESP", "RIyv": M4UserDataManager.m4UserShare.M4Itemcode, "HsYum": M4UserDataManager.m4UserShare.M4Token, "TNVhB": 2]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4recommendPros, .post, params: para), false) { model in
            self.M4endRefresh()
            loading.M4AlertViewHidden()
            self.recommendPros = []
            if model.code == 1 {
                let data = model.data as? [String : Any]
                let list = data?["SpiVwKO"] as? [[String : Any]]
                self.recommendPros = list?.kj.modelArray(M4RecommendProsModel.self) ?? []
            }
            self.M4LoanResultDataSource()
        }
    }
    
}
